package com.lc;

import com.lc.midi.CommandHelper;
import com.lc.midi.keyEvent.KeyEvents;
import com.lc.midi.keyEvent.KeyEventsFactory;
import com.lc.midi.mid.Midi;
import com.lc.midi.mid.MidiException;
import com.lc.midi.mid.MidiFile;
import com.lc.midi.script.Config;
import com.lc.midi.script.IScript;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;

public class Main {

    public static Logger logger = new Logger();

    public static void main(String[] args)  {
        logger.i("程序来自BestJs，作者QQ:1952511149");

        CommandHelper commandHelper;
        try {
            commandHelper = new CommandHelper(args);
        } catch (Exception e) {
            return;
        }
        Config config = commandHelper.config;
        List<String> midis =commandHelper.midis;
        String scriptDir = commandHelper.scriptDir;
        if (midis.isEmpty()) {
            logger.w("请提供mid文件");
            return;
        }
        int i = 0;
        for (String mid : midis) {
            i++;
            File file = new File(mid);
            try {
                String path = make(config, file, scriptDir);
                logger.i(String.format("(%d/%d)制作成功：%s", i, midis.size(), path));
            } catch (IOException e) {
                logger.e(String.format("(%d/%d)制作失败：%s，原因：文件读写错误", i, midis.size(), file.getName()));
            } catch (MidiException e) {
                logger.e(String.format("(%d/%d)制作失败：%s，原因：mid错误(%s)", i, midis.size(), file.getName(), e.getMessage()));
            }
        }
        logger.i("制作完成");
    }

    /**
     * 制作一个脚本
     * @param config 配置
     * @param mid mid文件
     * @param scriptDir 输出文件夹
     * @return 脚本路径
     * @throws IOException
     * @throws MidiException
     */
    public static String make(Config config, File mid, String scriptDir) throws IOException, MidiException {
        KeyEvents events = new KeyEventsFactory().createDefaultKeyEvents(new Midi(new MidiFile(mid)));
        String script = Objects.requireNonNull(IScript.getIScript(config)).createScript(events, config);
        File file = new File(scriptDir, getScriptName(config, mid.getName()));
        if (!file.getParentFile().exists())
            file.getParentFile().mkdirs();
        OutputStreamWriter writer = new FileWriter(file, StandardCharsets.UTF_8);
        writer.write(script);
        writer.flush();
        writer.close();
        return file.getAbsolutePath();
    }

    private static String getScriptName(Config config, String midName){
        midName = midName.replaceAll(".mid", "");
        midName = midName.replaceAll(".MID", "");
        if (config.getKind() == "js") {
            midName += ".js";
        } else {
            midName += ".record";
        }
        return midName;
    }
}
